function figs = plotTfcData_Core( tfc, channelregions, cfg )

if ischar(tfc) % assume its a filename and load it..
    disp('Loading file..');
    load(tfc);
end

disp('Plotting figures..');
if (cfg.PlotPerRegion && ~isempty(channelregions))
    electrodeList = fieldnames(tfc.data);
    regionList = cell(size(electrodeList));
    for i=1:length(regionList)
        regionList{i} = channelregions{strcmp(channelregions(:,1), electrodeList{i}),2};
    end
    regions = unique(regionList);
    figs = [];
    for r = regions'
        region = cell2mat(r);
        electrodeSelection = electrodeList(strcmp(regionList, region));
        plotTitle = [tfc.subject ' ' tfc.epochs ' ' region];
        disp([' --> ' plotTitle]);
        fgs = PlotElectrodes(electrodeSelection, tfc, plotTitle, cfg);
        figs = [figs fgs]; % concat the list of figures
    end
else
    electrodeList = fieldnames(tfc.data);
    plotTitle = [tfc.subject ' ' tfc.epochs];
    disp([' --> ' plotTitle]);
    figs = PlotElectrodes(electrodeList, tfc, plotTitle, cfg);
end

end

function figs = PlotElectrodes(electrodeList, tfc, plotTitle, cfg )
figs = [];
map = [ repmat(1:8, 1, 3); ones(1,8), ones(1,8)*2, ones(1,8)*3 ];
plottedAxes = zeros(3,8); plotNr = 0;
minValue = NaN; maxValue = NaN;
pointer = 0;
for elecC = electrodeList'
    electrode = cell2mat(elecC);
    if pointer == 0
        figs(end+1) = figure; plotNr = plotNr + 1;
        pointer = 1;
    end
    [plottedAxes(map(2,pointer), map(1,pointer)) mnV mxV] = ...
        Plot(tfc.data.(electrode), tfc.times, electrode, map(2,pointer), map(1,pointer), 3, 8, true, cfg);
    maxValue = max([maxValue mxV]);
    minValue = min([minValue mnV]);
    if pointer == length(map)
        FinalizePlot(plotTitle, plotNr, [{'1'},{'1'},{'1'},{'1'},{'1'}], plottedAxes, minValue, maxValue, cfg);
        plottedAxes = zeros(3,8); minValue = NaN; maxValue = NaN;
        pointer = 0;
    else
        pointer = pointer + 1;
    end
end
if pointer~=0
    FinalizePlot(plotTitle, plotNr, [{'1'},{'1'},{'1'},{'1'},{'1'}], plottedAxes, minValue, maxValue, cfg);
end
end

function FinalizePlot(plotTitle, plotNr, legendItems, plottedAxes, minValue, maxValue, cfg)
title = [plotTitle ' (' num2str(plotNr) ')'];
if plottedAxes(1,1)~=0
    text('Parent',plottedAxes(1,1),'VerticalAlignment','bottom','Units','normalized',...
        'String',title,'Interpreter','none',...
        'Position',[0.5 1 0],...
        'HorizontalAlignment','left');
end
if plottedAxes(3,1)~=0
    legend(plottedAxes(3,1), 'Location', 'NorthEast');
%     legend(plottedAxes(3,1), '\theta 4-7Hz', '\alpha 7-13Hz', '\beta 13-30Hz', 'L\gamma 30-70Hz', 'H\gamma 70-130Hz');
    legend(plottedAxes(3,1), 'show');
    legend(plottedAxes(3,1), 'boxoff');
elseif plottedAxes(2,1)~=0
    legend(plottedAxes(2,1), 'Location', 'Best');
%     legend(plottedAxes(2,1), '\theta 4-7Hz', '\alpha 7-13Hz', '\beta 13-30Hz', 'L\gamma 30-70Hz', 'H\gamma 70-130Hz');
    legend(plottedAxes(2,1), 'show');
    legend(plottedAxes(2,1), 'boxoff');
end
for a = find(plottedAxes(:) ~= 0)'
    ylim(plottedAxes(a), [minValue maxValue]);
    xlim(plottedAxes(a), [-4000 4000]);
end

if cfg.SaveFigure
    saveFigure(gcf, cfg.SavePath, title, true);
    close(gcf);
end;

end


function [axisObj minValue maxValue] = Plot(tfcElectrodeData, tfcTimes, name, nPos, mPos, nMax, mMax, writeXTicks, cfg)
writeXTicks = writeXTicks | (mPos==mMax);
left = (nPos - 1) * 0.96/nMax + 0.02;
bottom = 1 - (mPos * 0.96/mMax) - 0.02;
width = 0.94/nMax;
height = 0.94/mMax;
subplot('Position',[left bottom width height])
series = [];

for i = 1:length(tfcElectrodeData)
    if strcmp(cfg.Smoothing.Type, 'Gaussian')
        smoothedTfcElectrodeData(i).mean = GaussianSmooth(tfcElectrodeData(i).mean, cfg.Smoothing.Width);
        series = [series, smoothedTfcElectrodeData(i).mean];
    else
        series = [series, tfcElectrodeData(i).mean];
    end
end
minValue = min(series(:));
maxValue = max(series(:));
hLines = plot(tfcTimes, series', 'LineWidth', 1.4);
legendDisplayNames = {'\theta 4-7Hz', '\alpha 7-13Hz', '\beta 13-30Hz', 'L\gamma 30-70Hz', 'H\gamma 70-130Hz'};
for i = 1:size(series,2)
%     error('Do this first!')
    set(hLines(i), 'DisplayName', legendDisplayNames{i});
    set(get(get(hLines(i),'Annotation'),'LegendInformation'),...
        'IconDisplayStyle','on'); % Include line from legend
end
hold on;
colors = get(gcf,'DefaultAxesColorOrder');
for i = 1:length(tfcElectrodeData)
    hDots = plot(tfcTimes(tfcElectrodeData(i).peaklocs), smoothedTfcElectrodeData(i).mean(tfcElectrodeData(i).peaklocs), 'o', 'MarkerFaceColor',colors(i,:),'MarkerSize',3);
    set(get(get(hDots,'Annotation'),'LegendInformation'),...
        'IconDisplayStyle','off'); % Exclude line from legend
end


% s = std(series);
% for i = 1:size(series,2)
%    n(:,i) = series(:,i) / s(i);
% end
% plot(n, 'LineWidth', 2);
% hold;
% for i=1:length(peaks)
%     plot(peaks{i}.idxs, peaks{i}.vals, 'o', 'MarkerFaceColor','r','MarkerSize',6)
% end

ylabel(name, ...
    'FontWeight','bold', ...
    'Units', 'normalized', ...
    'Position',[0.03,0.97,0], ...
    'Rotation', 0, ...
    'HorizontalAlignment','left', ...
    'VerticalAlignment','top');

set(gca, ... % 'YLim', [0.8 , 1.2], 'YTick',[0.8 0.9 1 1.1 1.2],...%     'YTick',[-2 -1 0 1 2],...
    'YGrid','on',...
    'XTick',[-4000, -3000, -2000, -1000, 0, 1000, 2000, 3000, 4000],...
    'XGrid','on', ...
    'FontSize', 6);

if writeXTicks
    set(gca, 'XTickLabel',{'','-3s','-2s','-1s','Marker','+1s','+2s','+3s',''});
else
    set(gca, 'XTickLabel',{'','','','','','','','',''});
end;

% if nPos==1
%     set(gca, 'YTickLabel',{'','','','-.2','','avg','','+.2','','',''});
% else
%     set(gca, 'YTickLabel',{'','','','','','','','','','',''});
% end

axisObj = gca;

end